﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies
{
    public static class Utility
    {
        public static string[] LookupStringToArray(object value)
        {
            if (value == null)
                return new string[] {};

            var lookupParts = value.ToString().Split(new[]{";#"}, StringSplitOptions.None);
            var ret = new List<string>();

            for (var i = 0; i < lookupParts.Length; i++)
                if (i == 0 || i % 2 == 0)
                    ret.Add(lookupParts[i]);

            return ret.ToArray();
        }
        public static void LogDataTable(DataTable table)
        {
            foreach(DataRow row in table.Rows)
            {
                Logger.LogInfo("LogDataTable(): starting row", "Utility");
                foreach (DataColumn col in table.Columns)
                {
                    Logger.LogInfo("LogDataTable(): " + col.ColumnName + ": " + row[col.ColumnName], "Utility");
                }
                Logger.LogInfo("LogDataTable(): row ended", "Utility");
            }
        }
        public static void RemoveAll(this SPAttachmentCollection coll)
        {
            var items = new string[coll.Count];

            for (var i = 0; i < coll.Count; i++)
                items[i] = coll[i];

            foreach (string attachment in items)
                coll.Delete(attachment);
        }
        public static string Nl2Br(this string instr)
        {
            return instr.Replace("\n", "<br/>").Replace("\r", string.Empty);
        }
        public static Control FindControl(this Control control, string name, bool recursive)
        {
            if (!recursive)
                return control.FindControl(name);

            foreach (Control child in control.Controls)
            {
                if (child.ID == name)
                    return child;
                var ctl = child.FindControl(name, recursive);
                if (ctl != null)
                    return ctl;
            }
            return null;
        }
        public static List<ListItem> SelectedItems(this CheckBoxList checkList)
        {
            var items = new List<ListItem>();
            foreach (ListItem item in checkList.Items)
                if (item.Selected)
                    items.Add(item);

            return items;
        }
        public static SPListItem GetProfile(this SPUser user)
        {
            string queryString = "<Where><Eq><FieldRef Name=\"SysID\" /><Value Type=\"Text\">{0}</Value></Eq></Where>";
            queryString = string.Format(queryString, user.ToString().Substring(7));

            SPQuery query = new SPQuery();
            query.Query = queryString;

            SPListItemCollection items = SPContext.Current.Site.RootWeb.Lists["ProfileList"].GetItems(query);
            if (items.Count == 0)
                return null;
            return items[0];
        }
        public static bool HasCompany(this SPUser user)
        {
            var siteId = SPContext.Current.Web.Site.ID;
            var hasCompany = false;
            var sec = new SPSecurity.CodeToRunElevated(delegate
                       {
                           using(var site = new SPSite(siteId))
                           using (var web = site.OpenWeb("/firmad/"))
                           {
                               var queryString = "<Where><Or><Eq><FieldRef Name='Author' LookupId='True' /><Value Type='User'>{0}</Value></Eq>";
                               queryString += "<Eq><FieldRef Name='RealAuthor' LookupId='True' /><Value Type='User'>{1}</Value></Eq></Or></Where>";

                               var query = new SPQuery();
                               query.Query = string.Format(queryString, user.ID, user.ID);

                               var list = web.GetList("/firmad/Lehed/");
                               var items = list.GetItems(query);

                               if (items == null)
                               {
                                   hasCompany = false;
                                   return;
                               }
                               hasCompany = (items.Count > 0);
                           }
                       });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return hasCompany;
        }
        public static byte[] ToWindows1257(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return new byte[] { };


            var defaultEncoding = Encoding.UTF8;
            var asciiEncoding = Encoding.GetEncoding("windows-1257");
            var bytes = defaultEncoding.GetBytes(input);

            return Encoding.Convert(defaultEncoding, asciiEncoding, bytes);
        }
    }
}
